package com.yesep.learn.mqtt.client.common.util;

import com.yesep.learn.mqtt.client.common.event.EventKey;
import com.yesep.learn.mqtt.client.common.event.EventType;
import com.yesep.learn.mqtt.client.common.event.MqttEvent;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * save values to channel
 */
@Slf4j
public final class ChannelUtil {

	private static final AttributeKey<String> CLIENT_ID = AttributeKey.newInstance("CLIENT_ID");

	private ChannelUtil() {
	}

	public static void clientId(Channel channel, String clientId) {
		channel.attr(CLIENT_ID).set(clientId);
	}

	public static String clientId(Channel channel) {
		return channel.attr(CLIENT_ID).get();
	}

	public static void triggerUserEvent(ChannelHandlerContext ctx, EventType type, MqttMessage message) {
		EventKey key = new EventKey(type, ChannelUtil.clientId(ctx.channel()));
		MqttEvent event = new MqttEvent(key, message);
		ctx.fireUserEventTriggered(event);
		log.debug("trigger user event : {}", key);
	}
}
